<template>
  <div
    class="relative w-full h-full"
    v-loading="loading"
    :element-loading-text="loadingText"
    element-loading-background="rgba(0, 0, 0, 0.7)"
  >
    <div class="box-border w-full h-full p-16 px-10">
      <div class="flex items-center justify-between">
        <div class="flex gap-4">
          <div
            class="flex items-center justify-center custom-button5"
            :class="{ 'custom-button6': curIndex === item.id }"
            @click="changeCurIndex(item.id)"
            v-for="item in buttons"
            :key="item.id"
          >
            {{ item.name }}
          </div>
        </div>
        <div class="flex items-center justify-center gap-4">
          <div class="flex items-center justify-center custom-button" @click="exportSettingParams">
            输出设置参数
          </div>
          <div class="flex items-center justify-center custom-button" @click="exportChart">
            导出图片
          </div>
          <div class="flex items-center justify-center custom-button" @click="openExportDialog">
            导出数据
          </div>
        </div>
      </div>
      <div>
        <div class="relative">
          <Transition name="fade-transform" mode="out-in">
            <div v-if="curIndex === 1" class="absolute w-full mt-6">
              <div v-if="simulationStore.curPipeLine === '全线'" class="flex items-center">
                <span class="mr-4">预测管道</span>
                <el-select v-model="allLinePipe" placeholder="请选择预测管道" style="width: 220px">
                  <el-option
                    v-for="item in allLinePipeList"
                    :key="item.id"
                    :label="item.value"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div v-else class="flex items-center">
                <span class="mr-4">预测管道</span>
                <el-select
                  disabled
                  v-model="simulationStore.predictPipeline"
                  placeholder="请选择预测管道"
                  style="width: 220px"
                >
                  <el-option
                    v-for="item in pipelineList"
                    :key="item.id"
                    :label="item.value"
                    :value="item.value"
                  />
                </el-select>
              </div>
              <div class="flex items-center mt-4">
                <div class="flex items-center ml-auto">
                  <span class="mr-6">时间进度条</span>
                  <div class="flex items-center gap-4">
                    <el-button
                      :icon="isPlaying ? VideoPause : VideoPlay"
                      circle
                      @click="togglePlay"
                    />
                    <el-slider
                      v-model="timeProgress"
                      :min="0"
                      :max="simulationTime * 60"
                      :step="chartTimeInterval"
                      :format-tooltip="formatTimeTooltip"
                      @change="handleTimeProgressChange"
                    />
                  </div>
                </div>
              </div>
              <div class="flex justify-end mt-4">
                <div class="flex items-center">
                  <div
                    class="flex justify-center items-center w-10 h-10 bg-[#c1d1e4] rounded-full !border-[#638dbc] !border-2"
                  >
                    <img
                      src="../../assets/images/refresh3.png"
                      class="w-6 h-6 cursor-pointer refresh-icon"
                      :style="{ transform: `rotate(${rotationDegree}deg)` }"
                      @click="refreshTime"
                    />
                  </div>
                  <div class="flex items-center ml-4">
                    <el-input v-model="day" class="!w-[60px]" type="number" :min="0" :max="60" />
                    <span class="mx-2">天</span>
                    <el-input v-model="hour" class="!w-[60px]" type="number" :min="0" :max="24" />
                    <span class="mx-2">时</span>
                    <el-input-number
                      v-model="minute"
                      class="!w-[100px]"
                      @change="handleMinuteChange"
                      :step="chartTimeInterval"
                      :step-strictly="false"
                    />
                    <span class="mx-2">分</span>
                    <!-- <el-input v-model="second" class="!w-[60px]" type="number" :min="0" :max="60" />
                    <span class="mx-2">秒</span> -->
                  </div>
                </div>
              </div>
              <div v-show="!isShowQGQYX" class="flex justify-between" style="height: 500px">
                <v-chart
                  ref="chartRef1"
                  :option="chart1Options"
                  style="width: 32%; height: 100%"
                  :autoresize="true"
                />
                <v-chart
                  ref="chartRef2"
                  :option="chart2Options"
                  style="width: 32%; height: 100%"
                  :autoresize="true"
                />
                <v-chart
                  ref="chartRef3"
                  :option="chart3Options"
                  style="width: 32%; height: 100%"
                  :autoresize="true"
                />
              </div>
              <div v-show="isShowQGQYX" class="flex justify-between" style="height: 500px">
                <v-chart
                  ref="chartRef1Copy"
                  :option="chart1CopyOptions"
                  style="width: 32%; height: 100%"
                  :autoresize="true"
                />
                <v-chart
                  ref="chartRef4"
                  :option="chart4Options"
                  style="width: 32%; height: 100%"
                  :autoresize="true"
                />
                <div style="width: 32%; height: 80%" class="p-4">
                  <div class="mb-4 text-base font-bold text-center">清管器运行参数表</div>
                  <table
                    v-if="simulationStore.curPipeLine === '全线'"
                    class="w-full h-full border border-collapse"
                  >
                    <thead>
                      <tr>
                        <th class="bg-gray-100 border">运行参数</th>
                        <th class="bg-gray-100 border">乌百线</th>
                        <th class="bg-gray-100 border">百克线</th>
                        <th class="bg-gray-100 border">调油一线</th>
                        <th class="bg-gray-100 border">81线</th>
                      </tr>
                    </thead>
                    <tbody>
                      <tr>
                        <td class="w-1/5 text-center border">清管器运移速度（m/s）</td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.v_pig0"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.v_pig1"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.v_pig2"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.v_pig3"
                            class="no-style-input !text-base"
                          />
                        </td>
                      </tr>
                      <tr>
                        <td class="w-1/5 text-center border">管内油品流速（m/s）</td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.v_oil0"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.v_oil1"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.v_oil2"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.v_oil3"
                            class="no-style-input !text-base"
                          />
                        </td>
                      </tr>
                      <tr>
                        <td class="w-1/5 text-center border">距管道起点的距离（km）</td>
                        <td class="border">
                          <el-input v-model="qx_QGQParams.LOC0" class="no-style-input !text-base" />
                        </td>
                        <td class="border">
                          <el-input v-model="qx_QGQParams.LOC1" class="no-style-input !text-base" />
                        </td>
                        <td class="border">
                          <el-input v-model="qx_QGQParams.LOC2" class="no-style-input !text-base" />
                        </td>
                        <td class="border">
                          <el-input v-model="qx_QGQParams.LOC3" class="no-style-input !text-base" />
                        </td>
                      </tr>
                      <tr>
                        <td class="w-1/5 text-center border">距管道终点的距离（km）</td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.RLOC0"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.RLOC1"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.RLOC2"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.RLOC3"
                            class="no-style-input !text-base"
                          />
                        </td>
                      </tr>
                      <tr>
                        <td class="w-1/5 text-center border">预计到达终点时间（h）</td>
                        <td class="border">
                          <el-input v-model="qx_QGQParams.ETA0" class="no-style-input !text-base" />
                        </td>
                        <td class="border">
                          <el-input v-model="qx_QGQParams.ETA1" class="no-style-input !text-base" />
                        </td>
                        <td class="border">
                          <el-input v-model="qx_QGQParams.ETA2" class="no-style-input !text-base" />
                        </td>
                        <td class="border">
                          <el-input v-model="qx_QGQParams.ETA3" class="no-style-input !text-base" />
                        </td>
                      </tr>
                      <tr>
                        <td class="w-1/5 text-center border">到达终点剩余时间（h）</td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.RETA0"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.RETA1"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.RETA2"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.RETA3"
                            class="no-style-input !text-base"
                          />
                        </td>
                      </tr>
                      <tr>
                        <td class="w-1/5 text-center border">距终点的剩余管道容积（m3）</td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.RVOL0"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.RVOL1"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.RVOL2"
                            class="no-style-input !text-base"
                          />
                        </td>
                        <td class="border">
                          <el-input
                            v-model="qx_QGQParams.RVOL3"
                            class="no-style-input !text-base"
                          />
                        </td>
                      </tr>
                    </tbody>
                  </table>
                  <table v-else class="w-full h-full border border-collapse">
                    <tbody>
                      <tr>
                        <td class="w-2/3 text-center border">清管器运移速度（m/s）</td>
                        <td class="border">
                          <el-input v-model="QGQParams.v_pig" class="no-style-input !text-base" />
                        </td>
                      </tr>
                      <tr>
                        <td class="w-2/3 text-center border">管内油品流速（m/s）</td>
                        <td class="border">
                          <el-input v-model="QGQParams.v_oil" class="no-style-input !text-base" />
                        </td>
                      </tr>
                      <tr>
                        <td class="w-2/3 text-center border">距管道起点的距离（km）</td>
                        <td class="border">
                          <el-input v-model="QGQParams.LOC" class="no-style-input !text-base" />
                        </td>
                      </tr>
                      <tr>
                        <td class="w-2/3 text-center border">距管道终点的距离（km）</td>
                        <td class="border">
                          <el-input v-model="QGQParams.RLOC" class="no-style-input !text-base" />
                        </td>
                      </tr>
                      <tr>
                        <td class="w-2/3 text-center border">预计到达终点时间（h）</td>
                        <td class="border">
                          <el-input v-model="QGQParams.ETA" class="no-style-input !text-base" />
                        </td>
                      </tr>
                      <tr>
                        <td class="w-2/3 text-center border">到达终点剩余时间（h）</td>
                        <td class="border">
                          <el-input v-model="QGQParams.RETA" class="no-style-input !text-base" />
                        </td>
                      </tr>
                      <tr>
                        <td class="w-2/3 text-center border">距终点的剩余管道容积（m3）</td>
                        <td class="border">
                          <el-input v-model="QGQParams.RVOL" class="no-style-input !text-base" />
                        </td>
                      </tr>
                    </tbody>
                  </table>
                </div>
              </div>
            </div>
          </Transition>

          <Transition name="fade-transform" mode="out-in">
            <div v-if="curIndex === 2" class="absolute w-full mt-6">
              <div class="flex items-start mt-4">
                <div>
                  <div class="flex items-center">
                    <span class="w-16 mr-4">预测管道</span>
                    <el-select
                      v-model="simulationStore.predictPipeline"
                      placeholder="请选择预测管道"
                      style="width: 220px"
                    >
                      <el-option
                        :disabled="simulationStore.curPipeLine === '单一'"
                        v-for="item in pipelineList"
                        :key="item.id"
                        :label="item.value"
                        :value="item.value"
                      />
                    </el-select>
                  </div>
                  <div class="flex items-center mt-4">
                    <span class="w-16 mr-4">站场选择</span>
                    <el-select v-model="station" placeholder="请选择站场" style="width: 220px">
                      <el-option
                        v-for="item in curStationList"
                        :key="item"
                        :label="item"
                        :value="item"
                      />
                    </el-select>
                    <div class="flex items-center ml-10">
                      <span class="mr-6">安全限制</span>
                      <el-select
                        v-model="chartConditions"
                        multiple
                        collapse-tags
                        collapse-tags-tooltip
                        placeholder="请选择"
                        style="width: 200px"
                      >
                        <el-option
                          v-for="item in chartOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                          :disabled="item.disabled"
                        />
                      </el-select>
                    </div>
                  </div>
                </div>

                <div class="flex items-center ml-20">
                  <el-checkbox-group v-model="conditions2" class="flex-1">
                    <el-checkbox
                      :disabled="station.includes('首站')"
                      label="进站温度"
                      value="进站温度"
                    />
                    <el-checkbox
                      :disabled="station.includes('末站')"
                      label="出站温度"
                      value="出站温度"
                    />
                    <el-checkbox
                      :disabled="station.includes('首站')"
                      label="进站流量"
                      value="进站流量"
                    />
                    <el-checkbox
                      :disabled="station.includes('末站')"
                      label="出站流量"
                      value="出站流量"
                    />
                    <el-checkbox
                      :disabled="station.includes('首站')"
                      label="进站压力"
                      value="进站压力"
                    />
                    <el-checkbox
                      :disabled="station.includes('末站')"
                      label="出站压力"
                      value="出站压力"
                    />
                  </el-checkbox-group>
                </div>
              </div>
              <div class="flex justify-between mt-6" style="height: 500px">
                <v-chart
                  ref="chartRef4Temperature"
                  :option="chart4TemperatureOptions"
                  style="width: 32%; height: 100%"
                  :autoresize="true"
                />
                <v-chart
                  ref="chartRef4Flow"
                  :option="chart4FlowOptions"
                  style="width: 32%; height: 100%"
                  :autoresize="true"
                />
                <v-chart
                  ref="chartRef4Pressure"
                  :option="chart4PressureOptions"
                  style="width: 32%; height: 100%"
                  :autoresize="true"
                />
              </div>
            </div>
          </Transition>

          <Transition name="fade-transform" mode="out-in">
            <div v-if="curIndex === 3" class="w-full mt-6">
              <div>
                <div class="flex w-full gap-52">
                  <div class="flex items-center w-96" :class="{ 'opacity-0': !isShowResult }">
                    <div class="flex items-center gap-4 mr-4">
                      <img :src="rightIcon" class="w-6 h-5" />
                      最小安全输量
                    </div>
                    <el-input
                      readonly
                      v-model="min_flow_pump_speed.flow"
                      class="!w-32 mr-4"
                    ></el-input>
                    <span>m³/h</span>
                  </div>
                  <div>
                    <div class="flex items-center w-96">
                      <div class="flex items-center gap-4 mr-4">
                        <img :src="rightIcon" class="w-6 h-5" />
                        最大安全输量
                      </div>
                      <el-input
                        readonly
                        v-model="max_flow_pump_speed.flow"
                        class="!w-32 mr-4"
                      ></el-input>
                      <span>m³/h</span>
                    </div>
                    <div class="flex items-center mt-2 w-96">
                      <span class="ml-10 mr-4">最大出站压力</span>
                      <el-input
                        readonly
                        v-model="max_flow_pump_speed.pressure"
                        class="!w-32 mr-4"
                      ></el-input>
                      <span>MPa</span>
                    </div>
                  </div>
                  <div class="flex items-center w-96">
                    <div class="flex items-center gap-4 mr-4">
                      <img :src="rightIcon" class="w-6 h-5" />
                      安全停输时间
                    </div>
                    <el-input readonly v-model="safeStopTime" class="!w-32 mr-4"></el-input>
                    <span>h</span>
                  </div>
                </div>
                <div class="flex gap-52">
                  <div v-if="isShowResult" class="mt-4 text-base shadow-md w-96">
                    <div class="flex h-[60px]">
                      <div
                        class="box-border flex items-center justify-center w-48 border bg_table_header"
                      ></div>
                      <div
                        class="box-border flex items-center justify-center w-16 topBorder bottomBorder rightBorder bg_table_header"
                      >
                        1#
                      </div>
                      <div
                        class="box-border flex items-center justify-center w-16 bg_table_header topBorder bottomBorder rightBorder"
                      >
                        2#
                      </div>
                      <div
                        class="box-border flex items-center justify-center w-16 bg_table_header topBorder bottomBorder rightBorder"
                      >
                        3#
                      </div>
                    </div>
                    <div class="flex h-[60px]">
                      <div
                        class="box-border flex items-center justify-center w-48 leftBorder bottomBorder bg_table_header rightBorder"
                      >
                        泵转速(RPM)
                      </div>
                      <div class="box-border flex items-center w-16 px-2 rightBorder bottomBorder">
                        <el-input
                          readonly
                          v-model="min_flow_pump_speed.pump1_rpm"
                          class="no-style-input !text-base"
                        />
                      </div>
                      <div class="box-border flex items-center w-16 px-2 rightBorder bottomBorder">
                        <el-input
                          readonly
                          v-model="min_flow_pump_speed.pump2_rpm"
                          class="no-style-input !text-base"
                        />
                      </div>
                      <div class="box-border flex items-center w-16 px-2 rightBorder bottomBorder">
                        <el-input
                          readonly
                          v-model="min_flow_pump_speed.pump3_rpm"
                          class="no-style-input !text-base"
                        />
                      </div>
                    </div>
                    <div class="flex h-[60px]">
                      <div
                        class="box-border flex items-center justify-center w-48 leftBorder bottomBorder bg_table_header rightBorder"
                      >
                        过泵流量(m³/h)
                      </div>
                      <div class="box-border flex items-center w-16 px-2 rightBorder bottomBorder">
                        <el-input
                          readonly
                          v-model="min_flow_pump_speed.pump1_q"
                          class="no-style-input !text-base"
                        />
                      </div>
                      <div class="box-border flex items-center w-16 px-2 rightBorder bottomBorder">
                        <el-input
                          readonly
                          v-model="min_flow_pump_speed.pump2_q"
                          class="no-style-input !text-base"
                        />
                      </div>
                      <div class="box-border flex items-center w-16 px-2 rightBorder bottomBorder">
                        <el-input
                          readonly
                          v-model="min_flow_pump_speed.pump3_q"
                          class="no-style-input !text-base"
                        />
                      </div>
                    </div>
                  </div>
                  <div
                    v-else
                    class="h-[180px] mt-4 p-4 pt-10 box-border max-w-md bg-white rounded-lg shadow-md relative"
                  >
                    <div class="flex absolute -top-[44px] gap-4 items-center mr-4">
                      <img :src="rightIcon" class="w-6 h-5" />
                      最小安全输量
                    </div>

                    <div class="flex flex-col items-start gap-2 text-center text-gray-600">
                      <div>
                        当前地温为
                        <strong class="text-red-500">{{ T_g || '- -' }}</strong> ℃
                      </div>
                      <div>
                        首站出站温度为
                        <strong class="text-red-500">{{ T_S_OUT || '- -' }}</strong> ℃ 时
                      </div>
                      <div>
                        所有输量下末站进站温度均高于最小进站温度
                        <strong class="text-red-500">{{ T_m_min || '- -' }}</strong> ℃
                      </div>
                    </div>
                  </div>
                  <div class="mt-4 text-base shadow-md w-96">
                    <div class="flex h-[60px]">
                      <div
                        class="box-border flex items-center justify-center w-48 border bg_table_header"
                      ></div>
                      <div
                        class="box-border flex items-center justify-center w-16 topBorder bottomBorder rightBorder bg_table_header"
                      >
                        1#
                      </div>
                      <div
                        class="box-border flex items-center justify-center w-16 bg_table_header topBorder bottomBorder rightBorder"
                      >
                        2#
                      </div>
                      <div
                        class="box-border flex items-center justify-center w-16 bg_table_header topBorder bottomBorder rightBorder"
                      >
                        3#
                      </div>
                    </div>
                    <div class="flex h-[60px]">
                      <div
                        class="box-border flex items-center justify-center w-48 leftBorder bottomBorder bg_table_header rightBorder"
                      >
                        泵转速(RPM)
                      </div>
                      <div class="box-border flex items-center w-16 px-2 rightBorder bottomBorder">
                        <el-input
                          readonly
                          v-model="max_flow_pump_speed.pump1_rpm"
                          class="no-style-input !text-base"
                        />
                      </div>
                      <div class="box-border flex items-center w-16 px-2 rightBorder bottomBorder">
                        <el-input
                          readonly
                          v-model="max_flow_pump_speed.pump2_rpm"
                          class="no-style-input !text-base"
                        />
                      </div>
                      <div class="box-border flex items-center w-16 px-2 rightBorder bottomBorder">
                        <el-input
                          readonly
                          v-model="max_flow_pump_speed.pump3_rpm"
                          class="no-style-input !text-base"
                        />
                      </div>
                    </div>
                    <div class="flex h-[60px]">
                      <div
                        class="box-border flex items-center justify-center w-48 leftBorder bottomBorder bg_table_header rightBorder"
                      >
                        过泵流量(m³/h)
                      </div>
                      <div class="box-border flex items-center w-16 px-2 rightBorder bottomBorder">
                        <el-input
                          readonly
                          v-model="max_flow_pump_speed.pump1_q"
                          class="no-style-input !text-base"
                        />
                      </div>
                      <div class="box-border flex items-center w-16 px-2 rightBorder bottomBorder">
                        <el-input
                          readonly
                          v-model="max_flow_pump_speed.pump2_q"
                          class="no-style-input !text-base"
                        />
                      </div>
                      <div class="box-border flex items-center w-16 px-2 rightBorder bottomBorder">
                        <el-input
                          readonly
                          v-model="max_flow_pump_speed.pump3_q"
                          class="no-style-input !text-base"
                        />
                      </div>
                    </div>
                  </div>
                </div>

                <div class="border w-[488px] h-[400px] absolute left-0 top-[340px]">
                  <div class="h-full">
                    <v-chart
                      ref="safeStopTimeChartRef2"
                      :option="safeStopTimeChartOptions2"
                      style="width: 100%; height: 100%"
                      :autoresize="true"
                    />
                  </div>
                </div>

                <div class="border w-[488px] h-[400px] absolute left-[550px] top-[340px]">
                  <div class="h-full">
                    <v-chart
                      ref="safeStopTimeChartRef"
                      :option="safeStopTimeChartOptions"
                      style="width: 100%; height: 100%"
                      :autoresize="true"
                    />
                  </div>
                </div>

                <div class="border w-[488px] h-[400px] absolute left-[1050px] top-32">
                  <div class="h-full">
                    <v-chart
                      ref="minStartPressureChartRef"
                      :option="minStartPressureChartOptions"
                      style="width: 100%; height: 100%"
                      :autoresize="true"
                    />
                  </div>
                </div>
              </div>
            </div>
          </Transition>

          <div
            class="absolute top-[650px] left-1/2 -translate-x-1/2 w-[60vw]"
            v-if="
              curIndex === 1 &&
              simulationStore.batch_data?.length > 0 &&
              simulationStore.batch_data_ty?.length === 0
            "
          >
            <BarLine
              :batchData="simulationStore.batch_data"
              :batchDataTy="simulationStore.batch_data_ty"
              :wb_oil="simulationStore.wb_oil"
              :currentTime="timeProgress"
              :isPlaying="isPlaying"
              :timeInterval="chartTimeInterval"
              ref="barLineRef"
            />
          </div>

          <div
            class="absolute top-[650px] left-1/2 -translate-x-1/2 w-[60vw]"
            v-if="
              curIndex === 1 &&
              allLinePipe === '乌尔禾-百克站-701-总站' &&
              simulationStore.batch_data_ty?.length > 0
            "
          >
            <BarLineAll
              :batchData="simulationStore.batch_data"
              :batchDataTy="simulationStore.batch_data_ty"
              :wb_oil="simulationStore.wb_oil"
              :currentTime="timeProgress"
              :isPlaying="isPlaying"
              :timeInterval="chartTimeInterval"
              ref="barLineRef"
            />
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      v-model="exportDialogVisible"
      title="导出数据"
      width="500px"
      center
      :show-close="true"
      @close="closeExportDialog"
    >
      <div class="flex flex-col gap-8">
        <div class="flex flex-col gap-4">
          <div class="text-lg font-medium">时间选择</div>
          <div class="flex items-center justify-center gap-4">
            <el-input v-model="exportTime.startDay" class="!w-[60px]" />
            <span>天</span>
            <el-input v-model="exportTime.startHour" class="!w-[60px]" />
            <span>时</span>
            <el-input v-model="exportTime.startMinute" class="!w-[60px]" />
            <span>分</span>
            <el-input v-model="exportTime.startSecond" class="!w-[60px]" />
            <span>秒</span>
          </div>
          <div class="text-base leading-4 text-center">至</div>
          <div class="flex items-center justify-center gap-4">
            <el-input v-model="exportTime.endDay" class="!w-[60px]" />
            <span>天</span>
            <el-input v-model="exportTime.endHour" class="!w-[60px]" />
            <span>时</span>
            <el-input v-model="exportTime.endMinute" class="!w-[60px]" />
            <span>分</span>
            <el-input v-model="exportTime.endSecond" class="!w-[60px]" />
            <span>秒</span>
          </div>
        </div>

        <div class="flex flex-col gap-4">
          <div class="text-lg font-medium">参数选择</div>
          <el-checkbox-group v-model="exportParams">
            <div class="flex gap-4">
              <el-checkbox label="温度" size="large">温度</el-checkbox>
              <el-checkbox label="压力" size="large">压力</el-checkbox>
              <el-checkbox label="流量" size="large">流量</el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
      </div>

      <template #footer>
        <div class="flex justify-center gap-4">
          <el-button
            type="primary"
            color="rgba(155, 222, 246, 1)"
            :icon="Check"
            @click="handleExport"
            >导出</el-button
          >
          <el-button :icon="Close" @click="closeExportDialog">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  MarkLineComponent,
  DataZoomComponent
} from 'echarts/components'
import VChart, { THEME_KEY } from 'vue-echarts'
import { provide } from 'vue'

use([
  CanvasRenderer,
  LineChart,
  BarChart,
  GridComponent,
  TooltipComponent,
  LegendComponent,
  TitleComponent,
  MarkLineComponent,
  DataZoomComponent
])

provide(THEME_KEY, 'light')
import rightIcon from '@/assets/images/rightIcon.png'
import { initializeConstants } from './parameters'
import {
  getTemperatureChartOption,
  getPressureChartOption,
  getFlowChartOption,
  getCombinedPressureFlowChartOption,
  getPressureTimeChartOption,
  getTemperatureTimeChartOption,
  getFlowTimeChartOption,
  getSafeStopTimeChartOption,
  getSafeStopTimeChartOption2,
  getMinStartPressureChartOption,
  getPressureTimeChartOptionFachi1,
  getPressureTimeChartOptionFachi2,
  getPressureTimeChartOptionFachi3,
  getPressureTimeChartOptionFachi4,
  getPressureTimeChartOptionFachi5,
  getPressureTimeChartOptionFachi6,
  getFlowTimeChartOptionFachi1,
  getFlowTimeChartOptionFachi2,
  getFlowTimeChartOptionFachi3,
  getFlowTimeChartOptionFachi4,
  getFlowTimeChartOptionFachi5,
  getFlowTimeChartOptionFachi6,
  getTemperatureTimeChartOptionFachi1,
  getTemperatureTimeChartOptionFachi2,
  getTemperatureTimeChartOptionFachi3,
  getTemperatureTimeChartOptionFachi4,
  getTemperatureTimeChartOptionFachi5,
  getTemperatureTimeChartOptionFachi6
} from './chart-options'
import BarLine from './components/BarLine.vue'
import BarLineAll from './components/BarLine_all.vue'
import { Check, Close, VideoPause, VideoPlay } from '@element-plus/icons-vue'
import { utils as XLSXUtils, writeFile as XLSXWriteFile } from 'xlsx'
import { useSimulationStore } from '@/stores/modules/simulation'
import { nextTick, watch } from 'vue'

const route = useRoute()
const simulationStore = useSimulationStore()

const distance_variation_data = computed(() => simulationStore.distance_variation_data)
const time_variation_data = computed(() => simulationStore.time_variation_data)
const chartTimeInterval = computed(() => simulationStore.chartTimeInterval)
const simulationTime = computed(() => simulationStore.simulationTime)

const curIndex = ref(1)

const chart1Options = ref(getTemperatureChartOption(0))
const chart2Options = ref(getPressureChartOption(0))
const chart3Options = ref(getFlowChartOption(0))
const chart4Options = ref(getCombinedPressureFlowChartOption(0))
const chart1CopyOptions = ref(getTemperatureChartOption(0))
const chart4PressureOptions = ref(getPressureTimeChartOption())
const chart4TemperatureOptions = ref(getTemperatureTimeChartOption())
const chart4FlowOptions = ref(getFlowTimeChartOption())
const minStartPressureChartOptions = ref({})
const safeStopTimeChartOptions = ref({})
const safeStopTimeChartOptions2 = ref({})

let WEH_OUT_TEMP_LOW
let WEH_OUT_TEMP_HIGH
let WEH_OUT_PRESS_HIGH
let BKZ_OUT_TEMP_LOW
let BKZ_OUT_TEMP_HIGH
let BKZ_OUT_PRESS_HIGH
let BKZ_IN_TEMP_LOW
let BKZ_IN_PRESS_LOW
let BKZ_IN_PRESS_HIGH
let NEW81_OUT_TEMP_LOW
let NEW81_OUT_TEMP_HIGH
let NEW81_OUT_PRESS_HIGH
let NEW701_81_IN_TEMP_LOW
let NEW701_81_IN_PRESS_LOW
let NEW701_81_IN_PRESS_HIGH
let NEW701_BK_IN_TEMP_LOW
let NEW701_BK_IN_PRESS_LOW
let NEW701_BK_IN_PRESS_HIGH
let NEW701_OUT_TEMP_LOW
let NEW701_OUT_TEMP_HIGH
let NEW701_OUT_PRESS_HIGH
let ZZ_IN_TEMP_LOW
let ZZ_IN_PRESS_LOW
let ZZ_IN_PRESS_HIGH

const changeCurIndex = (id) => {
  curIndex.value = id

  if (id === 2) {
    nextTick(() => {
      chart4PressureOptions.value = getPressureTimeChartOption()
      chart4TemperatureOptions.value = getTemperatureTimeChartOption()
      chart4FlowOptions.value = getFlowTimeChartOption()
      conditions2.value = ['出站温度', '出站流量', '出站压力']
    })
  } else if (id === 1) {
    nextTick(() => {
      chart1Options.value = getTemperatureChartOption(timeProgress.value)
      chart1CopyOptions.value = getTemperatureChartOption(timeProgress.value)
      chart2Options.value = getPressureChartOption(timeProgress.value)
      chart3Options.value = getFlowChartOption(timeProgress.value)
      chart4Options.value = getCombinedPressureFlowChartOption(timeProgress.value)
    })
  }
}

const buttons = ref([
  {
    id: 1,
    name: '水热力空间变化趋势'
  },
  {
    id: 2,
    name: '水热力时间变化趋势 '
  },
  {
    id: 3,
    name: '运行安全决策'
  }
])
const timeProgress = ref(0)

// 全线的时候管道为乌尔禾-百克站-701-总站和81#站
const allLinePipe = ref('乌尔禾-百克站-701-总站')
const allLinePipeList = [
  { id: 1, value: '乌尔禾-百克站-701-总站' },
  { id: 2, value: '81#站' }
]
watch(allLinePipe, (val) => {
  if (simulationStore.curPipeLine === '全线') {
    if (val === '乌尔禾-百克站-701-总站') {
      simulationStore.distance_variation_data = simulationStore.distance_qx1
    } else {
      simulationStore.distance_variation_data = simulationStore.distance_qx2
    }
    refreshTime()
  }
})

const pipelineList = [
  { id: 1, value: '乌百线（乌尔禾站-百克站）' },
  { id: 2, value: '百克线（百克站-701站）' },
  { id: 3, value: '调油一线（701站-总站）' },
  { id: 4, value: '新81#线（81#站-701）' }
]

const station = ref('')
const conditions2 = ref(['出站温度', '出站流量', '出站压力'])

const chartConditions = ref([])
const chartOptions = ref([
  {
    value: '进站温度低值',
    label: '进站温度低值',
    disabled: false
  },
  {
    value: '出站温度低值',
    label: '出站温度低值',
    disabled: false
  },
  {
    value: '出站温度高值',
    label: '出站温度高值',
    disabled: false
  },
  {
    value: '进站压力低值',
    label: '进站压力低值',
    disabled: false
  },
  {
    value: '进站压力高值',
    label: '进站压力高值',
    disabled: false
  },
  {
    value: '出站压力高值',
    label: '出站压力高值',
    disabled: false
  }
])

const drawMarkLine = (chartOption, boundText, bound, unit) => {
  chartOption.series.push({
    name: `${boundText}`,
    type: 'line',
    markLine: {
      silent: true,
      symbol: ['none', 'none'],
      label: {
        formatter: `${boundText}: ${bound || 0}${unit}`,
        position: 'insideStartTop',
        color: '#FF4500',
        fontSize: 12,
        fontWeight: 'bold'
      },
      data: [
        {
          yAxis: bound || 0,
          lineStyle: {
            color: '#FF4500',
            type: 'dashed'
          }
        }
      ]
    }
  })
}

watch(
  [station, chartConditions, conditions2],
  ([newStation, newChartConditions, newConditions2]) => {
    let temperatureOption = {}
    temperatureOption =
      newStation === '阀池1#'
        ? getTemperatureTimeChartOptionFachi1()
        : newStation === '阀池2#'
          ? getTemperatureTimeChartOptionFachi2()
          : newStation === '阀池3#'
            ? getTemperatureTimeChartOptionFachi3()
            : getTemperatureTimeChartOption()

    let maxTemp = 60

    temperatureOption.series = temperatureOption.series.filter((series) => {
      if (series.name === '进站温度') {
        return newConditions2.includes('进站温度')
      }
      if (series.name === '出站温度') {
        return newConditions2.includes('出站温度')
      }
      if (series.markLine) {
        return true
      }
      return false
    })

    maxTemp = Math.max(maxTemp, WEH_OUT_TEMP_HIGH + 5)
    temperatureOption.yAxis.max = maxTemp
    if (simulationStore.predictPipeline === '乌百线（乌尔禾站-百克站）') {
      if (newChartConditions.includes('进站温度低值') && newStation === '百克站（末站）') {
        drawMarkLine(temperatureOption, '进站温度低值', BKZ_IN_TEMP_LOW, '℃')
      }
      if (newChartConditions.includes('出站温度低值') && newStation === '乌尔禾稀油站（首站）') {
        drawMarkLine(temperatureOption, '出站温度低值', WEH_OUT_TEMP_LOW, '℃')
      }

      if (newChartConditions.includes('出站温度高值') && newStation === '乌尔禾稀油站（首站）') {
        drawMarkLine(temperatureOption, '出站温度高值', WEH_OUT_TEMP_HIGH, '℃')
      }
    }

    if (simulationStore.predictPipeline === '百克线（百克站-701站）') {
      if (newChartConditions.includes('进站温度低值') && newStation === '701站（末站）') {
        drawMarkLine(temperatureOption, '进站温度低值', NEW701_BK_IN_TEMP_LOW, '℃')
      }
      if (newChartConditions.includes('出站温度低值') && newStation === '百克站（首站）') {
        drawMarkLine(temperatureOption, '出站温度低值', BKZ_OUT_TEMP_LOW, '℃')
      }

      if (newChartConditions.includes('出站温度高值') && newStation === '百克站（首站）') {
        drawMarkLine(temperatureOption, '出站温度高值', BKZ_OUT_TEMP_HIGH, '℃')
      }
    }

    if (simulationStore.predictPipeline === '新81#线（81#站-701）') {
      if (newChartConditions.includes('进站温度低值') && newStation === '701站（末站）') {
        drawMarkLine(temperatureOption, '进站温度低值', NEW701_81_IN_TEMP_LOW, '℃')
      }
      if (newChartConditions.includes('出站温度低值') && newStation === '81#站（首站）') {
        drawMarkLine(temperatureOption, '出站温度低值', NEW81_OUT_TEMP_LOW, '℃')
      }

      if (newChartConditions.includes('出站温度高值') && newStation === '81#站（首站）') {
        drawMarkLine(temperatureOption, '出站温度高值', NEW81_OUT_TEMP_HIGH, '℃')
      }
    }
    if (simulationStore.predictPipeline === '调油一线（701站-总站）') {
      if (newChartConditions.includes('进站温度低值') && newStation === '总站（末站）') {
        drawMarkLine(temperatureOption, '进站温度低值', ZZ_IN_TEMP_LOW, '℃')
      }
      if (newChartConditions.includes('出站温度低值') && newStation === '701站（首站）') {
        console.log('🐯 ~ NEW701_OUT_TEMP_LOW:', NEW701_OUT_TEMP_LOW)
        drawMarkLine(temperatureOption, '出站温度低值', NEW701_OUT_TEMP_LOW, '℃')
      }

      if (newChartConditions.includes('出站温度高值') && newStation === '701站（首站）') {
        console.log('🐯 ~ NEW701_OUT_TEMP_HIGH:', NEW701_OUT_TEMP_HIGH)
        drawMarkLine(temperatureOption, '出站温度高值', NEW701_OUT_TEMP_HIGH, '℃')
      }
    }

    chart4TemperatureOptions.value = temperatureOption

    let flowOption = {}
    flowOption =
      newStation === '阀池1#'
        ? getFlowTimeChartOptionFachi1()
        : newStation === '阀池2#'
          ? getFlowTimeChartOptionFachi2()
          : newStation === '阀池3#'
            ? getFlowTimeChartOptionFachi3()
            : getFlowTimeChartOption()

    flowOption.series = flowOption.series.filter((series) => {
      if (series.markLine) {
        return true
      }
      return newConditions2.includes('进站流量') || newConditions2.includes('出站流量')
    })
    chart4FlowOptions.value = flowOption

    let pressureOption = {}
    pressureOption =
      newStation === '阀池1#'
        ? getPressureTimeChartOptionFachi1()
        : newStation === '阀池2#'
          ? getPressureTimeChartOptionFachi2()
          : newStation === '阀池3#'
            ? getPressureTimeChartOptionFachi3()
            : getPressureTimeChartOption()

    let maxPressure = 1.2
    pressureOption.series = pressureOption.series.filter((series) => {
      if (series.name === '进站压力') {
        return newConditions2.includes('进站压力')
      }
      if (series.name === '出站压力') {
        return newConditions2.includes('出站压力')
      }
      if (series.markLine) {
        return true
      }
      return false
    })
    maxPressure = Math.max(maxPressure, WEH_OUT_PRESS_HIGH + 1)
    pressureOption.yAxis.max = maxPressure
    if (simulationStore.predictPipeline === '乌百线（乌尔禾站-百克站）') {
      if (newChartConditions.includes('进站压力低值') && newStation === '百克站（末站）') {
        drawMarkLine(pressureOption, '进站压力低值', BKZ_IN_PRESS_LOW, 'MPa')
      }

      if (newChartConditions.includes('进站压力高值') && newStation === '百克站（末站）') {
        drawMarkLine(pressureOption, '进站压力高值', BKZ_IN_PRESS_HIGH, 'MPa')
      }

      if (newChartConditions.includes('出站压力高值') && newStation === '乌尔禾稀油站（首站）') {
        drawMarkLine(pressureOption, '出站压力高值', WEH_OUT_PRESS_HIGH, 'MPa')
      }
    }

    if (simulationStore.predictPipeline === '百克线（百克站-701站）') {
      if (newChartConditions.includes('进站压力低值') && newStation === '701站（末站）') {
        drawMarkLine(pressureOption, '进站压力低值', NEW701_BK_IN_PRESS_LOW, 'MPa')
      }

      if (newChartConditions.includes('进站压力高值') && newStation === '701站（末站）') {
        drawMarkLine(pressureOption, '进站压力高值', NEW701_BK_IN_PRESS_HIGH, 'MPa')
      }

      if (newChartConditions.includes('出站压力高值') && newStation === '百克站（首站）') {
        drawMarkLine(pressureOption, '出站压力高值', BKZ_OUT_PRESS_HIGH, 'MPa')
      }
    }

    if (simulationStore.predictPipeline === '新81#线（81#站-701）') {
      if (newChartConditions.includes('进站压力低值') && newStation === '701站（末站）') {
        drawMarkLine(pressureOption, '进站压力低值', NEW701_81_IN_PRESS_LOW, 'MPa')
      }

      if (newChartConditions.includes('进站压力高值') && newStation === '701站（末站）') {
        drawMarkLine(pressureOption, '进站压力高值', NEW701_81_IN_PRESS_HIGH, 'MPa')
      }

      if (newChartConditions.includes('出站压力高值') && newStation === '81#站（首站）') {
        drawMarkLine(pressureOption, '出站压力高值', NEW81_OUT_PRESS_HIGH, 'MPa')
      }
    }

    if (simulationStore.predictPipeline === '调油一线（701站-总站）') {
      if (newChartConditions.includes('进站压力低值') && newStation === '总站（末站）') {
        drawMarkLine(pressureOption, '进站压力低值', ZZ_IN_PRESS_LOW, 'MPa')
      }

      if (newChartConditions.includes('进站压力高值') && newStation === '总站（末站）') {
        console.log('🐯 ~ ZZ_IN_PRESS_HIGH:', ZZ_IN_PRESS_HIGH)
        drawMarkLine(pressureOption, '进站压力高值', ZZ_IN_PRESS_HIGH, 'MPa')
      }

      if (newChartConditions.includes('出站压力高值') && newStation === '701站（首站）') {
        drawMarkLine(pressureOption, '出站压力高值', NEW701_OUT_PRESS_HIGH, 'MPa')
      }
    }

    chart4PressureOptions.value = pressureOption
  },
  { deep: true }
)

const isRotating = ref(false)
const rotationDegree = ref(0)

const barLineRef = ref(null)
const refreshTime = () => {
  console.log('refresh time')
  isRotating.value = true
  rotationDegree.value += 360
  setTimeout(() => {
    isRotating.value = false
  }, 100)

  if (timer.value) {
    clearInterval(timer.value)
  }

  currentIndex = 0
  currentTime.value = 0
  day.value = '0'
  hour.value = '0'
  minute.value = '0'
  second.value = '0'
  timeProgress.value = 0 // 重置时间进度

  nextTick(() => {
    chart1Options.value = getTemperatureChartOption(0)
    chart1CopyOptions.value = getTemperatureChartOption(0)
    chart2Options.value = getPressureChartOption(0)
    chart3Options.value = getFlowChartOption(0)
    chart4Options.value = getCombinedPressureFlowChartOption(0)

    startTimer()
    if (simulationStore.batch_data.length > 0) {
      console.log('重置barLine')
      if (barLineRef.value) {
        barLineRef.value.refreshData()
      }
    }
  })
}

const day = ref('0')
const hour = ref('0')
const minute = ref('0')
const second = ref('0')

const exportDialogVisible = ref(false)
const exportTime = ref({
  startDay: '0',
  startHour: '0',
  startMinute: '0',
  startSecond: '0',
  endDay: '0',
  endHour: simulationTime.value,
  endMinute: '0',
  endSecond: '0'
})
const exportParams = ref([])

const openExportDialog = () => {
  if (curIndex.value === 2) {
    const workbook = XLSXUtils.book_new()

    const headers = [
      '时间(分钟)',
      '出站压力(MPa)',
      '进站压力(MPa)',
      '出站温度(°C)',
      '进站温度(°C)',
      '流量(m³/h)'
    ]

    const tableData = time_variation_data.value.map((item) => [
      item.time,
      item.p_weh,
      item.p_bkz,
      item.t_weh,
      item.t_bkz,
      item.q_weh
    ])

    const worksheet = XLSXUtils.aoa_to_sheet([headers, ...tableData])
    XLSXUtils.book_append_sheet(workbook, worksheet, '时间变化趋势')

    XLSXWriteFile(workbook, `时间变化趋势数据_${station.value || '全部站场'}.xlsx`)
  } else if (curIndex.value === 3) {
    // exportDialogVisible.value = true
  } else {
    exportDialogVisible.value = true
  }
}

const closeExportDialog = () => {
  exportDialogVisible.value = false
  exportTime.value = {
    startDay: '0',
    startHour: '0',
    startMinute: '0',
    startSecond: '0',
    endDay: '0',
    endHour: simulationTime.value,
    endMinute: '0',
    endSecond: '0'
  }
  exportParams.value = []
}

const handleExport = () => {
  const workbook = XLSXUtils.book_new()

  const startMinutes =
    Number(exportTime.value.startDay) * 24 * 60 +
    Number(exportTime.value.startHour) * 60 +
    Number(exportTime.value.startMinute) +
    Number(exportTime.value.startSecond) / 60

  const endMinutes =
    Number(exportTime.value.endDay) * 24 * 60 +
    Number(exportTime.value.endHour) * 60 +
    Number(exportTime.value.endMinute) +
    Number(exportTime.value.endSecond) / 60

  const timePoints = []
  for (let t = startMinutes; t <= endMinutes; t += 10) {
    timePoints.push(t)
  }

  const distances = [...new Set(distance_variation_data.value.map((item) => item.distance))]

  exportParams.value.forEach((param) => {
    const tableData = distances.map((distance) => {
      const row = [distance]
      timePoints.forEach((time) => {
        const dataPoint = distance_variation_data.value.find(
          (item) => item.time === time && Math.abs(item.distance - distance) < 0.0001
        )
        let value = ''
        if (dataPoint) {
          switch (param) {
            case '温度':
              value = dataPoint.temperature
              break
            case '压力':
              value = dataPoint.pressure
              break
            case '流量':
              value = dataPoint.flow
              break
          }
        }
        row.push(value)
      })
      return row
    })

    const headers = ['距离', ...timePoints.map((t) => `${t}分钟`)]
    const worksheet = XLSXUtils.aoa_to_sheet([headers, ...tableData])
    XLSXUtils.book_append_sheet(workbook, worksheet, param)
  })

  const startTimeStr = `${exportTime.value.startDay}天${exportTime.value.startHour}时${exportTime.value.startMinute}分${exportTime.value.startSecond}秒`
  const endTimeStr = `${exportTime.value.endDay}天${exportTime.value.endHour}时${exportTime.value.endMinute}分${exportTime.value.endSecond}秒`
  XLSXWriteFile(workbook, `空间变化趋势数据_${startTimeStr}_至_${endTimeStr}.xlsx`)

  closeExportDialog()
}

const chartRef1 = ref(null)
const chartRef2 = ref(null)
const chartRef3 = ref(null)
const chartRef1Copy = ref(null)
const chartRef4 = ref(null)
const chartRef4Pressure = ref(null)
const chartRef4Temperature = ref(null)
const chartRef4Flow = ref(null)

const safeStopTimeChartRef = ref(null)
const safeStopTimeChartRef2 = ref(null)
const minStartPressureChartRef = ref(null)

const currentTime = ref(0)
const timePoints = computed(() => {
  const points = []
  const simulationTimeInMinutes = simulationTime.value * 60
  const totalPoints = Math.floor(simulationTimeInMinutes / chartTimeInterval.value)
  for (let i = 0; i <= totalPoints; i++) {
    points.push(i * chartTimeInterval.value)
  }
  return points
})
let currentIndex = 0

const pig_data = computed(() => simulationStore.pig_data)
const qx_pig_data = computed(() => simulationStore.qx_pig_data)
const QGQParams = ref({
  v_pig: '',
  v_oil: '',
  LOC: '',
  RLOC: '',
  ETA: '',
  RETA: '',
  RVOL: ''
})
const qx_QGQParams = ref({
  // 乌百线参数
  v_pig0: '',
  v_oil0: '',
  LOC0: '',
  RLOC0: '',
  ETA0: '',
  RETA0: '',
  RVOL0: '',

  // 百克线参数
  v_pig1: '',
  v_oil1: '',
  LOC1: '',
  RLOC1: '',
  ETA1: '',
  RETA1: '',
  RVOL1: '',

  // 调油一线参数
  v_pig2: '',
  v_oil2: '',
  LOC2: '',
  RLOC2: '',
  ETA2: '',
  RETA2: '',
  RVOL2: '',

  // 81线参数
  v_pig3: '',
  v_oil3: '',
  LOC3: '',
  RLOC3: '',
  ETA3: '',
  RETA3: '',
  RVOL3: ''
})
const updateChartAndQGXParams = () => {
  const time = timePoints.value[currentIndex]
  currentTime.value = time
  timeProgress.value = time // 确保时间进度同步

  const totalMinutes = time
  day.value = Math.floor(totalMinutes / (24 * 60)).toString()
  hour.value = Math.floor((totalMinutes % (24 * 60)) / 60).toString()
  minute.value = Math.floor(totalMinutes % 60).toString()
  second.value = '0'

  if (simulationStore.curPipeLine === '全线') {
    qx_QGQParams.value = qx_pig_data.value[currentIndex] || {
      // 乌百线参数
      v_pig0: '',
      v_oil0: '',
      LOC0: '',
      RLOC0: '',
      ETA0: '',
      RETA0: '',
      RVOL0: '',

      // 百克线参数
      v_pig1: '',
      v_oil1: '',
      LOC1: '',
      RLOC1: '',
      ETA1: '',
      RETA1: '',
      RVOL1: '',

      // 调油一线参数
      v_pig2: '',
      v_oil2: '',
      LOC2: '',
      RLOC2: '',
      ETA2: '',
      RETA2: '',
      RVOL2: '',

      // 81线参数
      v_pig3: '',
      v_oil3: '',
      LOC3: '',
      RLOC3: '',
      ETA3: '',
      RETA3: '',
      RVOL3: ''
    }
  } else {
    QGQParams.value = pig_data.value[currentIndex] || {
      v_pig: '',
      v_oil: '',
      LOC: '',
      RLOC: '',
      ETA: '',
      RETA: '',
      RVOL: ''
    }
  }

  chart1Options.value = getTemperatureChartOption(time)
  chart1CopyOptions.value = getTemperatureChartOption(time)
  chart2Options.value = getPressureChartOption(time)
  chart3Options.value = getFlowChartOption(time)
  chart4Options.value = getCombinedPressureFlowChartOption(time)
}

const timer = ref(null)

const isPlaying = ref(true)

const startTimer = () => {
  // 如果已经有计时器在运行，先清除它
  if (timer.value) {
    clearInterval(timer.value)
  }

  isPlaying.value = true
  timer.value = setInterval(() => {
    // 检查是否到达最后一个时间点
    if (currentIndex >= timePoints.value.length - 1) {
      clearInterval(timer.value)
      timer.value = null
      isPlaying.value = false
      return
    }

    // 只有在播放状态下才更新
    if (isPlaying.value) {
      currentIndex++
      updateChartAndQGXParams()
    } else {
      // 如果不是播放状态，停止计时器
      clearInterval(timer.value)
      timer.value = null
    }
  }, 200)
}

const togglePlay = () => {
  if (isPlaying.value) {
    // 暂停播放
    if (timer.value) {
      clearInterval(timer.value)
      timer.value = null
    }
    isPlaying.value = false
  } else {
    // 当前不在播放状态，开始播放
    startTimer()
  }
}

const updateTimeAndChart = () => {
  const totalMinutes =
    Number(day.value) * 24 * 60 +
    Number(hour.value) * 60 +
    Number(minute.value) +
    Number(second.value) / 60

  if (totalMinutes >= 0 && totalMinutes <= simulationTime.value * 60) {
    timeProgress.value = Math.floor(totalMinutes)

    day.value = Math.floor(totalMinutes / (24 * 60)).toString()
    hour.value = Math.floor((totalMinutes % (24 * 60)) / 60).toString()
    minute.value = Math.floor(totalMinutes % 60).toString()
    second.value = Math.floor((totalMinutes % 1) * 60).toString()

    chart1Options.value = getTemperatureChartOption(totalMinutes)
    chart1CopyOptions.value = getTemperatureChartOption(totalMinutes)
    chart2Options.value = getPressureChartOption(totalMinutes)
    chart3Options.value = getFlowChartOption(totalMinutes)
    chart4Options.value = getCombinedPressureFlowChartOption(totalMinutes)
  }
}

watch([day, hour, minute, second], () => {
  if (
    day.value !== '' &&
    hour.value !== '' &&
    minute.value !== '' &&
    second.value !== '' &&
    !isPlaying.value
  ) {
    updateTimeAndChart()
  }
})
// 限制逻辑（不用 min/max）
const handleMinuteChange = (val) => {
  const maxMinute = simulationTime.value * 60 // 把小时转成分钟
  const curMinutes =
    Number(day.value) * 24 * 60 +
    Number(hour.value) * 60 +
    Number(minute.value) +
    Number(second.value) / 60
  if (curMinutes <= 0) {
    minute.value = 0
  } else if (curMinutes >= maxMinute) {
    day.value = Math.floor(maxMinute / (24 * 60)).toString()
    hour.value = Math.floor((maxMinute % (24 * 60)) / 60).toString()
    minute.value = Math.floor(maxMinute % 60).toString()
    second.value = Math.floor((maxMinute % 1) * 60).toString()
  }
}

const handleTimeProgressChange = (minutes) => {
  // 强制暂停播放
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
  isPlaying.value = false

  // 更新时间显示
  day.value = Math.floor(minutes / (24 * 60)).toString()
  hour.value = Math.floor((minutes % (24 * 60)) / 60).toString()
  minute.value = Math.floor(minutes % 60).toString()
  second.value = '0'

  // 更新当前索引和参数
  currentIndex = Math.floor(minutes / chartTimeInterval.value)
  timeProgress.value = minutes // 确保进度条显示正确

  // 更新清管器参数
  if (simulationStore.curPipeLine === '全线') {
    qx_QGQParams.value = qx_pig_data.value[currentIndex] || {
      // 乌百线参数
      v_pig0: '',
      v_oil0: '',
      LOC0: '',
      RLOC0: '',
      ETA0: '',
      RETA0: '',
      RVOL0: '',

      // 百克线参数
      v_pig1: '',
      v_oil1: '',
      LOC1: '',
      RLOC1: '',
      ETA1: '',
      RETA1: '',
      RVOL1: '',

      // 调油一线参数
      v_pig2: '',
      v_oil2: '',
      LOC2: '',
      RLOC2: '',
      ETA2: '',
      RETA2: '',
      RVOL2: '',

      // 81线参数
      v_pig3: '',
      v_oil3: '',
      LOC3: '',
      RLOC3: '',
      ETA3: '',
      RETA3: '',
      RVOL3: ''
    }
  } else {
    QGQParams.value = pig_data.value[currentIndex] || {
      v_pig: '',
      v_oil: '',
      LOC: '',
      RLOC: '',
      ETA: '',
      RETA: '',
      RVOL: ''
    }
  }

  // 更新图表
  chart1Options.value = getTemperatureChartOption(minutes)
  chart1CopyOptions.value = getTemperatureChartOption(minutes)
  chart2Options.value = getPressureChartOption(minutes)
  chart3Options.value = getFlowChartOption(minutes)
  chart4Options.value = getCombinedPressureFlowChartOption(minutes)
}

const exportChart = () => {
  let charts = []
  let timeStr = ''
  let chartNames = []

  if (curIndex.value === 1) {
    charts = [chartRef1.value, chartRef2.value, chartRef3.value]
    timeStr = `${day.value}天${hour.value}时${minute.value}分${second.value}秒`
    chartNames = ['温度', '压力', '流量']
  } else if (curIndex.value === 2) {
    charts = [chartRef4Pressure.value, chartRef4Temperature.value, chartRef4Flow.value]
    timeStr = `站场${station.value}`
    chartNames = ['压力', '温度', '流量']
  } else if (curIndex.value === 3) {
    charts = [
      safeStopTimeChartRef2.value,
      safeStopTimeChartRef.value,
      minStartPressureChartRef.value
    ]
    timeStr = `站场${station.value}`
    chartNames = ['最小安全输量', '最大安全输量', '安全停输时间']
  }

  charts.forEach((chart, index) => {
    if (chart) {
      const echartsInstance = chart.chart
      if (echartsInstance) {
        const imageURL = echartsInstance.getDataURL({
          type: 'png',
          pixelRatio: 2,
          backgroundColor: '#fff'
        })

        const fileName =
          curIndex.value === 1
            ? `水热力空间变化趋势_${chartNames[index]}_${timeStr}.png`
            : curIndex.value === 2
              ? `水热力时间变化趋势_${chartNames[index]}_${timeStr}.png`
              : `${chartNames[index]}_${timeStr}.png`

        const link = document.createElement('a')
        link.download = fileName
        link.href = imageURL
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }
    }
  })
}

const formatTimeTooltip = (minutes) => {
  const days = Math.floor(minutes / (24 * 60))
  const hours = Math.floor((minutes % (24 * 60)) / 60)
  const mins = Math.floor(minutes % 60)
  return `${days}天${hours}时${mins}分0秒`
}

onMounted(async () => {
  console.log('onMounted')
  const parametersConstants = await initializeConstants()
  WEH_OUT_TEMP_LOW = parametersConstants.WEH_OUT_TEMP_LOW
  WEH_OUT_TEMP_HIGH = parametersConstants.WEH_OUT_TEMP_HIGH
  WEH_OUT_PRESS_HIGH = parametersConstants.WEH_OUT_PRESS_HIGH

  BKZ_OUT_TEMP_LOW = parametersConstants.BKZ_OUT_TEMP_LOW
  BKZ_OUT_TEMP_HIGH = parametersConstants.BKZ_OUT_TEMP_HIGH
  BKZ_OUT_PRESS_HIGH = parametersConstants.BKZ_OUT_PRESS_HIGH

  BKZ_IN_TEMP_LOW = parametersConstants.BKZ_IN_TEMP_LOW
  BKZ_IN_PRESS_LOW = parametersConstants.BKZ_IN_PRESS_LOW
  BKZ_IN_PRESS_HIGH = parametersConstants.BKZ_IN_PRESS_HIGH

  NEW81_OUT_TEMP_LOW = parametersConstants.NEW81_OUT_TEMP_LOW
  NEW81_OUT_TEMP_HIGH = parametersConstants.NEW81_OUT_TEMP_HIGH
  NEW81_OUT_PRESS_HIGH = parametersConstants.NEW81_OUT_PRESS_HIGH

  NEW701_81_IN_TEMP_LOW = parametersConstants.NEW701_81_IN_TEMP_LOW
  NEW701_81_IN_PRESS_LOW = parametersConstants.NEW701_81_IN_PRESS_LOW
  NEW701_81_IN_PRESS_HIGH = parametersConstants.NEW701_81_IN_PRESS_HIGH

  NEW701_BK_IN_TEMP_LOW = parametersConstants.NEW701_BK_IN_TEMP_LOW
  NEW701_BK_IN_PRESS_LOW = parametersConstants.NEW701_BK_IN_PRESS_LOW
  NEW701_BK_IN_PRESS_HIGH = parametersConstants.NEW701_BK_IN_PRESS_HIGH

  ZZ_IN_PRESS_HIGH = parametersConstants.ZZ_IN_PRESS_HIGH
  ZZ_IN_PRESS_LOW = parametersConstants.ZZ_IN_PRESS_LOW
  ZZ_IN_TEMP_LOW = parametersConstants.ZZ_IN_TEMP_LOW

  NEW701_OUT_PRESS_HIGH = parametersConstants.NEW701_OUT_PRESS_HIGH
  NEW701_OUT_TEMP_HIGH = parametersConstants.NEW701_OUT_TEMP_HIGH
  NEW701_OUT_TEMP_LOW = parametersConstants.NEW701_OUT_TEMP_LOW

  console.log('🐯 ~ onMounted ~ parametersConstants:', parametersConstants)

  startTimer()
})

const isShowQGQYX = ref(false)

watch(
  () => route.query,
  (val, oldVal) => {
    console.log('🐯 ~ watch ~ val:', val)
    if (val.isQGQYX || pig_data.value.length > 0 || qx_pig_data.value.length > 0) {
      console.log('🐯 ~ pig_data.value:', pig_data.value)
      console.log('🐯 ~ val.isQGQYX:', val.isQGQYX)
      console.log('🐯 ~ qx_pig_data.value.length:', qx_pig_data.value.length)
      isShowQGQYX.value = true
    } else {
      isShowQGQYX.value = false
    }

    if (val.oils_id) {
      nextTick(() => {
        refreshTime()
      })
    }
  },

  { immediate: true }
)

onUnmounted(() => {
  if (timer.value) {
    clearInterval(timer.value)
    timer.value = null
  }
})

watch(
  () => simulationStore.temperature_time_variation,
  (newVal) => {
    minStartPressureChartOptions.value = getMinStartPressureChartOption(
      newVal.map((item) => item.time),
      newVal.map((item) => item.temperature)
    )
  }
)
watch(
  () => simulationStore.operating_parameters,
  (newVal) => {
    safeStopTimeChartOptions.value = getSafeStopTimeChartOption(
      newVal.map((item) => item.distance),
      newVal.map((item) => item.pressure),
      newVal.map((item) => item.flow)
    )
    safeStopTimeChartOptions2.value = getSafeStopTimeChartOption2(
      newVal.map((item) => item.distance),
      newVal.map((item) => item.temperature),
      newVal.map((item) => item.flow)
    )
  }
)

const loading = ref(false)
const loadingText = '加载中...'

const isShowResult = computed(() => simulationStore.isShowQmin)
const T_g = computed(() => simulationStore.T_g)
const T_S_OUT = computed(() => simulationStore.T_S_OUT)
const T_m_min = computed(() => simulationStore.T_m_min)
const min_flow_pump_speed = computed(() => simulationStore.min_flow_pump_speed)
const max_flow_pump_speed = computed(() => simulationStore.max_flow_pump_speed)
const safeStopTime = computed(() => simulationStore.safeStopTime)
// const temperature_time_variation = computed(() => simulationStore.temperature_time_variation)

const curStationList = ref([])
watch(
  () => simulationStore.predictPipeline,
  (newVal) => {
    console.log('🐯 ~ newVal:', newVal)
    if (newVal === '乌百线（乌尔禾站-百克站）') {
      curStationList.value = [
        '乌尔禾稀油站（首站）',
        '阀池1#',
        '阀池2#',
        '阀池3#',
        '百克站（末站）'
      ]
      station.value = '乌尔禾稀油站（首站）'
    } else if (newVal === '百克线（百克站-701站）') {
      curStationList.value = ['百克站（首站）', '阀池1#', '阀池2#', '阀池3#', '701站（末站）']
      station.value = '百克站（首站）'
    } else if (newVal === '新81#线（81#站-701）') {
      curStationList.value = ['81#站（首站）', '701站（末站）']
      station.value = '81#站（首站）'
    } else if (newVal === '调油一线（701站-总站）') {
      curStationList.value = ['701站（首站）', '总站（末站）']
      station.value = '701站（首站）'
    }
  },
  { immediate: true }
)

// watch(
//   () => simulationStore.curTGPipe,
//   (newVal) => {
//     simulationStore.predictPipeline = '风克线'
//     if (newVal === '风克线') {
//       curStationList.value = [
//         '风城首站',
//         '阀池1#',
//         '阀池2#',
//         '阀池3#',
//         '阀池4#',
//         '阀池5#',
//         '阀池6#',
//         '克石化末站'
//       ]
//       station.value = '风城首站'
//     }
//   },
//   {
//     immediate: true
//   }
// )

watch(
  station,
  (newVal) => {
    console.log('🐯 ~ newVal:', newVal)
    if (newVal.includes('首站')) {
      conditions2.value = ['出站温度', '出站流量', '出站压力']
      chartOptions.value = [
        {
          value: '进站温度低值',
          label: '进站温度低值',
          disabled: true
        },
        {
          value: '出站温度低值',
          label: '出站温度低值',
          disabled: false
        },
        {
          value: '出站温度高值',
          label: '出站温度高值',
          disabled: false
        },
        {
          value: '进站压力低值',
          label: '进站压力低值',
          disabled: true
        },
        {
          value: '进站压力高值',
          label: '进站压力高值',
          disabled: true
        },
        {
          value: '出站压力高值',
          label: '出站压力高值',
          disabled: false
        }
      ]
    } else if (newVal.includes('末站')) {
      conditions2.value = ['进站温度', '进站流量', '进站压力']
      chartOptions.value = [
        {
          value: '进站温度低值',
          label: '进站温度低值',
          disabled: false
        },
        {
          value: '出站温度低值',
          label: '出站温度低值',
          disabled: true
        },
        {
          value: '出站温度高值',
          label: '出站温度高值',
          disabled: true
        },
        {
          value: '进站压力低值',
          label: '进站压力低值',
          disabled: false
        },
        {
          value: '进站压力高值',
          label: '进站压力高值',
          disabled: false
        },
        {
          value: '出站压力高值',
          label: '出站压力高值',
          disabled: true
        }
      ]
    } else {
      conditions2.value = ['进站温度', '出站温度', '进站流量', '出站流量', '进站压力', '出站压力']
      chartOptions.value = [
        {
          value: '进站温度低值',
          label: '进站温度低值',
          disabled: false
        },
        {
          value: '出站温度低值',
          label: '出站温度低值',
          disabled: false
        },
        {
          value: '出站温度高值',
          label: '出站温度高值',
          disabled: false
        },
        {
          value: '进站压力低值',
          label: '进站压力低值',
          disabled: false
        },
        {
          value: '进站压力高值',
          label: '进站压力高值',
          disabled: false
        },
        {
          value: '出站压力高值',
          label: '出站压力高值',
          disabled: false
        }
      ]
      if (newVal === '阀池1#') {
        chart4PressureOptions.value = getPressureTimeChartOptionFachi1()
        chart4TemperatureOptions.value = getTemperatureTimeChartOptionFachi1()
        chart4FlowOptions.value = getFlowTimeChartOptionFachi1()
      } else if (newVal === '阀池2#') {
        chart4PressureOptions.value = getPressureTimeChartOptionFachi2()
        chart4TemperatureOptions.value = getTemperatureTimeChartOptionFachi2()
        chart4FlowOptions.value = getFlowTimeChartOptionFachi2()
      } else if (newVal === '阀池3#') {
        chart4PressureOptions.value = getPressureTimeChartOptionFachi3()
        chart4TemperatureOptions.value = getTemperatureTimeChartOptionFachi3()
        chart4FlowOptions.value = getFlowTimeChartOptionFachi3()
      } else if (newVal === '阀池4#') {
        chart4PressureOptions.value = getPressureTimeChartOptionFachi4()
        chart4TemperatureOptions.value = getTemperatureTimeChartOptionFachi4()
        chart4FlowOptions.value = getFlowTimeChartOptionFachi4()
      } else if (newVal === '阀池5#') {
        chart4PressureOptions.value = getPressureTimeChartOptionFachi5()
        chart4TemperatureOptions.value = getTemperatureTimeChartOptionFachi5()
        chart4FlowOptions.value = getFlowTimeChartOptionFachi5()
      } else if (newVal === '阀池6#') {
        chart4PressureOptions.value = getPressureTimeChartOptionFachi6()
        chart4TemperatureOptions.value = getTemperatureTimeChartOptionFachi6()
        chart4FlowOptions.value = getFlowTimeChartOptionFachi6()
      }
    }
  },
  { immediate: true }
)

// 输出设置参数
const exportSettingParams = async () => {
  await simulationStore.preditParams.download({
    format: 'png',
    filename: '参数设置'
  })
}
onDeactivated(() => {
  curIndex.value = 1
})
</script>

<style lang="scss" scoped>
.custom-button {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  padding: 2px 0px;
  font-size: 14px;
  border-radius: 4px;
  border: 1px solid #4678b2;
  color: #4678b2;
  background-color: #e8edf4;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    color: white;
    border-color: #5889bf;
    background-color: #4678b2;
  }
}

:deep(.el-slider) {
  width: 240px;
}

.refresh-icon {
  transition: transform 1s;
  transform: rotate(0deg);
  &.rotate {
    transform: rotate(360deg);
  }
}

:deep(.el-dialog__header) {
  font-weight: 700;
  height: 48px;
  line-height: 48px;
  padding: 0 !important;

  .el-dialog__title {
    font-size: 18px !important;
  }
}

.custom-button {
  background-color: rgba(69, 122, 178, 0.18);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border: 1px solid rgba(69, 122, 178, 1);
  border-radius: 6px;
  color: rgba(69, 122, 178, 0.8);
  width: 140px;
  height: 40px;

  cursor: pointer;
  &:hover {
    background-color: rgba(69, 122, 178, 1);
    border: 1px solid rgba(69, 122, 178, 1);
    color: white;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    border-radius: 6px;
  }
}
.custom-button5 {
  background-color: rgba(69, 122, 178, 0.18);
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border: 1px solid rgba(69, 122, 178, 1);
  border-radius: 6px;
  color: rgba(69, 122, 178, 0.8);
  width: 180px;
  height: 40px;
  cursor: pointer;
  &:hover {
    background-color: rgba(69, 122, 178, 1);
    border: 1px solid rgba(69, 122, 178, 1);
    color: white;
    background-size: 100% 100%;
    background-repeat: no-repeat;
    border-radius: 6px;
  }
}

.custom-button6 {
  background-color: rgba(69, 122, 178, 1);
  border: 1px solid rgba(69, 122, 178, 1);
  color: white;
  background-size: 100% 100%;
  background-repeat: no-repeat;
  border-radius: 6px;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: #fff;
}

.border {
  border: 1px solid black;
}
.leftBorder {
  border-left: 1px solid black;
}
.rightBorder {
  border-right: 1px solid black;
}
.bottomBorder {
  border-bottom: 1px solid black;
}
.topBorder {
  border-top: 1px solid black;
}
.bg_table_header {
  background-color: rgba(247, 247, 247, 1);
}

:deep(.no-style-input) {
  .el-input__wrapper {
    background: none;
    box-shadow: none;
    padding: 0;
  }

  .el-input__inner {
    border: none;
    background: none;
  }
}
:deep(.el-input__inner) {
  text-align: center;
}
</style>
